package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.domain.BaseBasketballPlayer;
import com.ruoyi.system.domain.BasketballPlayerAndTeam;
import com.ruoyi.system.domain.vo.BasketBallPlayerInviteVO;
import com.ruoyi.system.service.IBaseBasketballPlayerService;
import com.ruoyi.system.service.IBasketballPlayerAndTeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.mapper.BaseBasketballTeamMapper;
import com.ruoyi.system.domain.BaseBasketballTeam;
import com.ruoyi.system.service.IBaseBasketballTeamService;

import javax.annotation.Resource;

/**
 * 球队Service业务层处理
 *
 * @author wangbj
 * @date 2024-04-16
 */
@Service
public class BaseBasketballTeamServiceImpl extends ServiceImpl<BaseBasketballTeamMapper, BaseBasketballTeam> implements IBaseBasketballTeamService {
    @Resource
    private BaseBasketballTeamMapper baseBasketballTeamMapper;

    @Resource
    RedisService redisService;

    @Resource
    LoginUserSetUtil loginUserSetUtil;

    @Resource
    private TokenService tokenService;

    @Resource
    private IBasketballPlayerAndTeamService iBasketballPlayerAndTeamService;
    /**
     * 查询球队
     *
     * @param id 球队主键
     * @return 球队
     */
    @Override
    public BaseBasketballTeam selectBaseBasketballTeamById(Long id) {
        return baseBasketballTeamMapper.selectBaseBasketballTeamById(id);
    }

    /**
     * 查询球队列表
     *
     * @param baseBasketballTeam 球队
     * @return 球队
     */
    @Override
    public List<BaseBasketballTeam> selectBaseBasketballTeamList(BaseBasketballTeam baseBasketballTeam) {
        List<BaseBasketballTeam> baseBasketballTeams = baseBasketballTeamMapper.selectBaseBasketballTeamList(baseBasketballTeam);
        if (CollUtil.isEmpty(baseBasketballTeams)){
            return new ArrayList<>();
        }
        //主队和客队不能相同
        if (Objects.nonNull(baseBasketballTeam.getId())) {
            baseBasketballTeams = baseBasketballTeams.stream().filter(vo -> !Objects.equals(vo.getId(), baseBasketballTeam.getId())).collect(Collectors.toList());
        }
        Set<Long> teamIds = baseBasketballTeams.stream().map(BaseBasketballTeam::getId).collect(Collectors.toSet());

        List<BasketballPlayerAndTeam> list = iBasketballPlayerAndTeamService.list(Wrappers.<BasketballPlayerAndTeam>lambdaQuery()
                .in(BasketballPlayerAndTeam::getTeamId, teamIds)
                .eq(BasketballPlayerAndTeam::getType, 0)
        );
        Map<Long, List<BasketballPlayerAndTeam>> collect = list.stream().collect(Collectors.groupingBy(BasketballPlayerAndTeam::getTeamId));

        baseBasketballTeams.forEach(vo ->{
            List<BasketballPlayerAndTeam> basketballPlayerAndTeams = collect.get(vo.getId());
            if (CollUtil.isNotEmpty(basketballPlayerAndTeams)){
                vo.setNum(basketballPlayerAndTeams.size());
            }
        });
        return baseBasketballTeams;
    }

    /**
     * 新增球队
     *
     * @param baseBasketballTeam 球队
     * @return 结果
     */
    @Override
    public int insertBaseBasketballTeam(BaseBasketballTeam baseBasketballTeam) {
        if (StrUtil.isBlank(baseBasketballTeam.getTeamName())){
            return -1;
        }
        baseBasketballTeam.setCreateTime(DateUtils.getNowDate());

        LambdaQueryWrapper<BaseBasketballTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseBasketballTeam::getIsDeleted,0);
        queryWrapper.eq(BaseBasketballTeam::getTeamName,baseBasketballTeam.getTeamName());
        queryWrapper.eq(BaseBasketballTeam::getLeagueId,baseBasketballTeam.getLeagueId());
        queryWrapper.last("limit 1");
        BaseBasketballTeam basketballTeam = baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(basketballTeam)){
            return -1;
        }
        loginUserSetUtil.populateFields(baseBasketballTeam,1);
        int team = baseBasketballTeamMapper.insertBaseBasketballTeam(baseBasketballTeam);

        //更新成功后同步至redis
        if (team > 0) {
            BaseBasketballTeam baseBasketballTeams = baseMapper.selectBaseBasketballTeamList(baseBasketballTeam).get(0);
            redisService.setCacheObject(BaseTournamentServiceImpl.PREFIX.concat(String.valueOf(baseBasketballTeams.getId())), baseBasketballTeams);
        }
        return team;
    }

    /**
     * 修改球队
     *
     * @param baseBasketballTeam 球队
     * @return 结果
     */
    @Override
    public int updateBaseBasketballTeam(BaseBasketballTeam baseBasketballTeam) {
        baseBasketballTeam.setUpdateTime(DateUtils.getNowDate());

        LambdaQueryWrapper<BaseBasketballTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseBasketballTeam::getIsDeleted,0);
        queryWrapper.eq(BaseBasketballTeam::getTeamName,baseBasketballTeam.getTeamName());
        queryWrapper.eq(BaseBasketballTeam::getLeagueId,baseBasketballTeam.getLeagueId());
        queryWrapper.ne(BaseBasketballTeam::getId,baseBasketballTeam.getId());
        queryWrapper.last("limit 1");
        BaseBasketballTeam basketballTeam = baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(basketballTeam)){
            return -1;
        }
        loginUserSetUtil.populateFields(baseBasketballTeam,2);
        int team = baseBasketballTeamMapper.updateBaseBasketballTeam(baseBasketballTeam);

        //更新成功后同步至redis
        if (team > 0) {
            redisService.setCacheObject(BaseTournamentServiceImpl.PREFIX.concat(String.valueOf(baseBasketballTeam.getId())), baseBasketballTeam);
        }

        return team;
    }

    /**
     * 批量删除球队
     *
     * @param ids 需要删除的球队主键
     * @return 结果
     */
    @Override
    public int deleteBaseBasketballTeamByIds(Long[] ids) {

        //清除缓存
        for (int i = 0; i < ids.length; i++) {
            redisService.deleteObject(BaseTournamentServiceImpl.PREFIX.concat(String.valueOf(ids[i])));
        }

        return baseBasketballTeamMapper.deleteBaseBasketballTeamByIds(ids);
    }

    /**
     * 删除球队信息
     *
     * @param id 球队主键
     * @return 结果
     */
    @Override
    public int deleteBaseBasketballTeamById(Long id) {
        redisService.deleteObject(BaseTournamentServiceImpl.PREFIX.concat(String.valueOf(id)));

        return baseBasketballTeamMapper.deleteBaseBasketballTeamById(id);
    }

    @Override
    public String createBasketBallTeamInvite(BasketBallPlayerInviteVO basketBallPlayerInviteVO) {
        Long teamId = basketBallPlayerInviteVO.getTeamId();
        AssertUtil.notNull(teamId,"球队id不能为空");
        BaseBasketballTeam baseBasketballTeam = baseBasketballTeamMapper.selectById(teamId);
        AssertUtil.notNull(baseBasketballTeam,"球队没有找到!");
        String code = UUID.randomUUID().toString();
        //将唯一标识符存入缓存，邀请链接24小时过期
        redisService.setCacheObject("invite_join_team_" + code, teamId,24L, TimeUnit.HOURS);
        return "inviteJoinTeam?code=" + code;
    }

    @Override
    public Boolean agreeTeamInvite(BasketBallPlayerInviteVO basketBallPlayerInviteVO) {
        String code = basketBallPlayerInviteVO.getCode();
        AssertUtil.notEmpty(code,"标识码不能为空");
        //通过code获取要加入的球队id
        Long teamId;
        try {
            teamId = redisService.getCacheObject("invite_join_team_" + code);
        }catch (Exception e){
            throw new ServiceException("邀请链接已过期！");
        }

        LoginUser loginUser = tokenService.getLoginUser();
        BaseBasketballPlayer baseBasketballPlayer = new BaseBasketballPlayer();
        baseBasketballPlayer.setPlayerId(teamId);
        return null;
    }

    @Override
    public List<BaseBasketballTeam> playerTeamList(Long contestId,String teamName) {
        return baseMapper.selectList(Wrappers.<BaseBasketballTeam>lambdaQuery()
                .eq(Objects.nonNull(contestId),BaseBasketballTeam::getLeagueId,contestId)
                .eq(StringUtils.isNotBlank(teamName),BaseBasketballTeam::getTeamName,teamName)
                .eq(BaseBasketballTeam::getIsDeleted,0L)
                .orderByDesc(BaseBasketballTeam::getCreateTime)
        );
    }

    @Override
    public List<BaseBasketballTeam> selectByTeamName(Long contestId,Set<String> keySet) {
        return baseMapper.selectList(Wrappers.<BaseBasketballTeam>lambdaQuery()
                .eq(Objects.nonNull(contestId),BaseBasketballTeam::getLeagueId,contestId)
                .in(CollUtil.isNotEmpty(keySet),BaseBasketballTeam::getTeamName,keySet)
                .eq(BaseBasketballTeam::getIsDeleted,0L)
        );
    }
}
